package com.demo.filter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import com.demo.service.GetDNSService;
import com.demo.service.impl.GetDNSServiceImpl;
import com.demo.util.JudgeUtil;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;

@Component
public class ZuulFilterDemo extends ZuulFilter  {
	
	@Resource
	GetDNSService getDNSService;
	
	 private static List<String> urlMap=new ArrayList();
	@Override
	public boolean shouldFilter() {
		return true;
	}

	@Override
	public Object run() throws ZuulException {
		urlMap = getDNSService.getDNS();
		RequestContext ctx = RequestContext.getCurrentContext();
		HttpServletRequest request = ctx.getRequest();
		String url = request.getRequestURI(); // 列子 [/user/login/loginWx]
		String[] split = url.split("/", 3);	// 这里切割一下,好让下面判断是否是需要修改url的.
		if (split.length>=2) {
			if (JudgeUtil.ifInclude(urlMap, split[1])) {
				url=url.replaceFirst("/"+split[1]+"/", "/");// 根据配置好的去将url替换掉,这里可以写自己的转换url的规则
				ctx.put(FilterConstants.REQUEST_URI_KEY, url); // 将替换掉的url set进去,在对应的转发请求的url就会使用这个url
			}
		}
    	return null;
	}

	@Override
	public String filterType() {
		return FilterConstants.ROUTE_TYPE;
	}

	@Override
	public int filterOrder() {
		return 0;
	}

}
